/*
 * StopWatch.cpp
 *
 *  Created on: Jan 26, 2010
 *      Author: Jamie LaPointe
 */

#include "StopWatch.h"

using namespace LinuxStopWatch;

StopWatch::StopWatch() :
   isTimerSet(false), isTimerStopped(false),
         microsecondsInMilliseconds(1000.0), millisecondsInSeconds(1000.0)
{

}

int StopWatch::start()
{
   rusage ru;
   int retVal = getrusage(RUSAGE_SELF, &ru);
   if (retVal == noError)
   {
      timeradd(&(ru.ru_utime), &(ru.ru_stime), &(timer.start));
      isTimerSet = true;
      isTimerStopped = false;
   }
   return retVal;
}

int StopWatch::stop()
{
   int retVal = isTimerNotSet;
   if (isTimerSet)
   {
      rusage ru;
      retVal = getrusage(RUSAGE_SELF, &ru);
      if (retVal == noError)
      {
         timeradd(&(ru.ru_utime), &(ru.ru_stime), &(timer.stop));
         isTimerSet = true;
         isTimerStopped = true;
      }
   }
   return retVal;
}

//
// Returns the elapsed CPU time in milliseconds
//
double StopWatch::getElapsedTime()
{
   if (isTimerSet && !isTimerStopped)
   {
      stop();
   }

   if (isTimerSet && isTimerStopped)
   {
      timeval res;
      timersub(&(timer.stop), &(timer.start), &res);
      return (((double) res.tv_sec * millisecondsInSeconds)
            + ((double) res.tv_usec / microsecondsInMilliseconds));
   }
   else // this means timer never properly started.
   {
      return timerNeverStarted;
   }
}
